import { defineStore } from 'pinia'
import { getSessions, getChatHistory, createSession, type ChatHistoryResponse, type CreateSessionResponse } from '@/api/chat'

interface Message {
  type: 'user' | 'assistant'
  content: string
  timestamp?: string
}

interface SystemStatus {
  llm: boolean
  browser: boolean
  redis: boolean
}

interface Session {
  id: string
  name: string
  created_time: string
}

export const useChatStore = defineStore('chat', {
  state: () => ({
    messages: [] as Message[],
    sessionId: 'default',
    sessions: [] as Session[],
    systemStatus: {
      llm: false,
      browser: false,
      redis: false
    } as SystemStatus,
    // 添加滚动回调函数
    scrollToBottomCallback: null as (() => void) | null
  }),
  
  actions: {
    addMessage(message: Message) {
      this.messages.push({
        ...message,
        timestamp: message.timestamp || new Date().toISOString()
      })
    },

    updateMessageTimestamp(index: number, timestamp: string) {
      if (this.messages[index]) {
        this.messages[index].timestamp = timestamp
      }
    },
    
    setSessionId(id: string) {
      this.sessionId = id
      // 切换会话时保存到localStorage
      localStorage.setItem('currentSessionId', id)
    },
    
    clearMessages() {
      this.messages = []
    },
    
    updateSystemStatus(status: Partial<SystemStatus>) {
      this.systemStatus = {
        ...this.systemStatus,
        ...status
      }
    },

    // 设置滚动回调函数
    setScrollToBottomCallback(callback: (() => void) | null) {
      this.scrollToBottomCallback = callback
    },

    async loadSessions() {
      try {
        const response = await getSessions()
        this.sessions = response.sessions
        
        // 如果没有会话，创建默认会话
        if (this.sessions.length === 0) {
          await this.createNewSession()
        }
        
        // 从localStorage恢复当前会话ID
        const savedSessionId = localStorage.getItem('currentSessionId')
        if (savedSessionId && this.sessions.find(s => s.id === savedSessionId)) {
          this.sessionId = savedSessionId
        } else if (this.sessions.length > 0) {
          this.sessionId = this.sessions[0].id
          localStorage.setItem('currentSessionId', this.sessionId)
        }
        
        // 加载当前会话的历史消息
        await this.loadSessionHistory()
      } catch (error) {
        console.error('加载会话列表失败:', error)
      }
    },

    async loadSessionHistory() {
      try {
        const response: ChatHistoryResponse = await getChatHistory(this.sessionId)
        
        // 转换Redis历史记录为消息格式
        const messages: Message[] = []
        
        if (response.redis_history && response.redis_history.length > 0) {
          // 跳过第一条记录（通常是会话创建记录）
          const historyToProcess = response.redis_history.slice(1)
          
          for (const record of historyToProcess) {
            // 处理新格式：分离的用户消息和助手回复
            if (record.type === 'user' && record.user && record.user.trim() && record.user !== '会话创建') {
              messages.push({
                type: 'user',
                content: record.user,
                timestamp: record.user_timestamp || record.timestamp || new Date().toISOString()
              })
            } else if (record.type === 'assistant' && record.assistant && record.assistant.trim() && record.assistant !== '新会话已创建') {
              messages.push({
                type: 'assistant',
                content: record.assistant,
                timestamp: record.assistant_timestamp || record.timestamp || new Date().toISOString()
              })
            } else {
              // 兼容旧格式：用户消息和助手回复在同一条记录中
              if (record.user && record.user.trim() && record.user !== '会话创建') {
                messages.push({
                  type: 'user',
                  content: record.user,
                  timestamp: record.timestamp
                })
              }
              
              if (record.assistant && record.assistant.trim() && record.assistant !== '新会话已创建') {
                messages.push({
                  type: 'assistant',
                  content: record.assistant,
                  timestamp: record.timestamp
                })
              }
            }
          }
        }
        
        this.messages = messages
        
        // 切换会话后滚动到底部
        if (this.scrollToBottomCallback) {
          setTimeout(() => {
            this.scrollToBottomCallback?.()
          }, 100)
        }
        
      } catch (error) {
        console.error('加载会话历史失败:', error)
        this.messages = []
      }
    },

    async createNewSession() {
      try {
        const response: CreateSessionResponse = await createSession()
        // 先切换到新会话
        this.setSessionId(response.session_id)
        this.clearMessages() // 清空消息
        // 重新加载会话列表以获取最新的会话信息（包括时间戳）
        await this.loadSessions()
        return response.session_id
      } catch (error) {
        console.error('创建新会话失败:', error)
        throw error
      }
    },

    // 初始化store时自动加载数据
    async initialize() {
      await this.loadSessions()
    }
  }
})